package cn.mybatishelper.entity.xml;

import cn.mybatishelper.entity.CreateFile;
import cn.mybatishelper.entity.database.DatabaseEntity;
import cn.mybatishelper.entity.mybatis.MybatisElement;
import cn.mybatishelper.exception.MybatisHelperException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * mybatis的xml基类
 * User: GameKing
 */
public abstract class MybatisXmlEntity implements XmlEntity, CreateFile {
    private static final Logger LOGGER = LoggerFactory.getLogger(MybatisXmlEntity.class);
    /**
     * 需要生成的mybatis元素的集合
     */
    protected List<MybatisElement> elements;
    /**
     * 文件根路径，用于实例生成文件时的路径拼装
     */
    protected String rootFilePath;
    /**
     * mybatis的xml文件的头部元素
     */
    protected static final String title = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
    /**
     * mybatis的xml文件的头部元素
     */
    protected static final String docTitle = "<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\" >";


    protected MybatisXmlEntity() {
    }

    protected MybatisXmlEntity(String rootFilePath) {
        this.rootFilePath = rootFilePath;
    }

    protected MybatisXmlEntity(List<MybatisElement> elements) {
        this.elements = elements;
    }

    protected MybatisXmlEntity(List<MybatisElement> elements, String rootFilePath) {
        this.elements = elements;
        this.rootFilePath = rootFilePath;
    }

    @Override
    public void createFile(DatabaseEntity databaseEntity) throws MybatisHelperException {
        try {
            String content = this.getMybatisString(databaseEntity);
            String packageUrl = databaseEntity.getXmlPackageName().replaceAll("\\.", "/");
            File file = new File(rootFilePath + File.separator + packageUrl + File.separator + databaseEntity.getObjectName() + "Mapper.xml");
            FileUtils.writeStringToFile(file, content, "UTF-8");
        } catch (IOException e) {
            throw new MybatisHelperException("转化物理文件发生异常 : " + e.getMessage());
        }
    }

    @Override
    public boolean validateXmlElements() {
        if (CollectionUtils.isEmpty(elements)) {
            LOGGER.error("初始化Xml元素时，mybatis元素为空!");
            return false;
        }
        if (StringUtils.isBlank(rootFilePath)) {
            LOGGER.error("文件根路径不能为空");
            return false;
        }
        return true;
    }

    public List<MybatisElement> getElements() {
        return elements;
    }

    public void setElements(List<MybatisElement> elements) {
        this.elements = elements;
    }

    public String getRootFilePath() {
        return rootFilePath;
    }

    public void setRootFilePath(String rootFilePath) {
        this.rootFilePath = rootFilePath;
    }
}
